package com.sh.pangea.dsa.ui.fragment;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.sh.lib.bossstat.bean.WxUserStat;
import com.sh.lib.bossstat.callback.WXUserStateListener;
import com.sh.lib.bossstat.impl.BossStatManager;
import com.sh.lib.cmswifi.impl.CmsWifiManager;
import com.sh.pangea.dsa.R;
import com.sh.pangea.dsa.Utils.PreferenceUtil;
import com.sh.pangea.dsa.adapter.MonitoringAdapter;
import com.sh.pangea.dsa.ui.activity.NounExplanationActivity;
import com.sh.pangea.dsa.ui.activity.SelectHospitalActivity;
import com.sh.pangea.dsa.view.LoadingDialog;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import static com.umeng.socialize.utils.Log.TAG;

public class MonitoringFragment extends Fragment implements View.OnClickListener {
    public static final int CON_TIME_OUT = 1000;
    public static final int SO_TIME_OUT = 1000;
    MonitoringAdapter adapter;
    List<String> list = new ArrayList<>();
    List<String> adapterList = new ArrayList<>();
    private Context context;
    private String hospitalName = "全部";
    private String lastHospitalName;
    private String hospitalValue = "";
    private WxUserStat lastWxUserStat;

    TextView userCount;
    TextView devCount;
    TextView nowTime;
    TextView tvHospitol;
    Button btUpdata;
    ImageView ivTranslate;
    RelativeLayout rlSelectHospital;
    private ListView listViewShowData;
    private LoadingDialog loading;

    {
        list.add("当日新增用户数:");
        list.add("当日取关用户数:");
        list.add("当日新增设备数:");
        list.add("当日认证次数:");
        list.add("当日认证设备数:");
        list.add("当日放行次数:");
        list.add("当日放行设备数:");
        list.add("当日免认证次数:");
        list.add("当日免认证设备数:");
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View inflate = inflater.inflate(R.layout.fragment_monitoring, container, false);
        context = getActivity();
        initView(inflate);
        getWxUserStatus();
        return inflate;
    }

    private void initView(View view) {
        userCount = (TextView) view.findViewById(R.id.tv_user_value);
        tvHospitol = (TextView) view.findViewById(R.id.tv_hospital);
        rlSelectHospital = (RelativeLayout) view.findViewById(R.id.rl_hospital_select);
        rlSelectHospital.setClickable(true);
        rlSelectHospital.setOnClickListener(this);
        devCount = (TextView) view.findViewById(R.id.tv_dev_value);
        nowTime = (TextView) view.findViewById(R.id.tv_updata_time);
        btUpdata = (Button) view.findViewById(R.id.bt_updata);
        ivTranslate = (ImageView) view.findViewById(R.id.iv_translate);
        listViewShowData = (ListView) view.findViewById(R.id.lv_data_show);
        btUpdata.setOnClickListener(this);
        ivTranslate.setOnClickListener(this);
        rlSelectHospital.setOnClickListener(this);
        adapter = new MonitoringAdapter(context, list);
        listViewShowData.setAdapter(adapter);
        loading = new LoadingDialog(context);
    }

    private void initData(WxUserStat wxUserStat) {
        String cumulativeNumber = "";
        String cumulativeDeviceNumber = "";
        if (wxUserStat != null) {
            cumulativeNumber = wxUserStat.getCumulativeNumber();
            cumulativeDeviceNumber = wxUserStat.getCumulativeDeviceNumber();
            nowTime.setText(getNowTime());
            getAdapterData(wxUserStat);
            adapter.updata(adapterList);
        } else {
            adapter.updata(list);
        }
        if (!TextUtils.isEmpty(cumulativeNumber)) {
            userCount.setText(cumulativeNumber);
        } else {
            userCount.setText("--");
        }
        if (!TextUtils.isEmpty(cumulativeDeviceNumber)) {
            devCount.setText(cumulativeDeviceNumber);
        } else {
            devCount.setText("--");
        }
        adapter.notifyDataSetChanged();
    }

    /**
     * 通过bean 添加适配器数据
     */
    private void getAdapterData(WxUserStat wxUserStat) {
        adapterList.clear();
        String numberOfnNewday = wxUserStat.getNumberOfnNewday();
        if (!TextUtils.isEmpty(numberOfnNewday)) {
            adapterList.add(list.get(0) + numberOfnNewday);
        } else {
            adapterList.add(list.get(0));


        }

        String unsubscribeNumber = wxUserStat.getUnsubscribeNumber();
        if (!TextUtils.isEmpty(unsubscribeNumber)) {
            adapterList.add(list.get(1) + unsubscribeNumber);
        } else {
            adapterList.add(list.get(1));
        }

        String deviceNumber = wxUserStat.getDeviceNumber();
        if (!TextUtils.isEmpty(deviceNumber)) {
            adapterList.add(list.get(2) + deviceNumber);
        } else {
            adapterList.add(list.get(2));
        }


        String certificationTimes = wxUserStat.getCertificationTimes();
        if (!TextUtils.isEmpty(certificationTimes)) {
            adapterList.add(list.get(3) + certificationTimes);
        } else {
            adapterList.add(list.get(3));
        }

        String certificationDeviceTimes = wxUserStat.getCertificationDeviceTimes();
        if (!TextUtils.isEmpty(certificationDeviceTimes)) {
            adapterList.add(list.get(4) + certificationDeviceTimes);
        } else {
            adapterList.add(list.get(4));
        }

        String releaseTimes = wxUserStat.getReleaseTimes();
        if (!TextUtils.isEmpty(releaseTimes)) {
            adapterList.add(list.get(5) + releaseTimes);
        } else {
            adapterList.add(list.get(5));
        }

        String releaseDeviceTimes = wxUserStat.getReleaseDeviceTimes();
        if (!TextUtils.isEmpty(releaseDeviceTimes)) {
            adapterList.add(list.get(6) + releaseDeviceTimes);
        } else {
            adapterList.add(list.get(6));
        }

        String unCertificationTimes = wxUserStat.getUnCertificationTimes();
        if (!TextUtils.isEmpty(unCertificationTimes)) {
            adapterList.add(list.get(7) + unCertificationTimes);
        } else {
            adapterList.add(list.get(7));
        }

        String unCertificationDeviceTimes = wxUserStat.getUnCertificationDeviceTimes();
        if (!TextUtils.isEmpty(unCertificationDeviceTimes)) {
            adapterList.add(list.get(8) + unCertificationDeviceTimes);
        } else {
            adapterList.add(list.get(8));
        }


    }

    /**
     * 把接口返回的数据，按期望倍数放大
     *
     * @param wxUserStat 返回的数据
     * @return 新的数据
     */
    private WxUserStat amplifyData(WxUserStat wxUserStat) {
        if (wxUserStat == null) {
            Log.i("Main", "按期望倍数放大,现有数据为空");
            return new WxUserStat();
        }

        String numberOfnNewday = wxUserStat.getNumberOfnNewday();
        if (!TextUtils.isEmpty(numberOfnNewday)) {
            String string = changeData(numberOfnNewday);
            wxUserStat.setNumberOfnNewday(string);
        }

        String unsubscribeNumber = wxUserStat.getUnsubscribeNumber();
        if (!TextUtils.isEmpty(unsubscribeNumber)) {
            String string = changeData(unsubscribeNumber);
            wxUserStat.setUnsubscribeNumber(string);
        }

        String deviceNumber = wxUserStat.getDeviceNumber();
        if (!TextUtils.isEmpty(deviceNumber)) {
            String string = changeData(deviceNumber);
            wxUserStat.setDeviceNumber(string);
        }


        String certificationTimes = wxUserStat.getCertificationTimes();
        if (!TextUtils.isEmpty(certificationTimes)) {
            String string = changeData(certificationTimes);
            wxUserStat.setCertificationTimes(string);
        }

        String certificationDeviceTimes = wxUserStat.getCertificationDeviceTimes();
        if (!TextUtils.isEmpty(certificationDeviceTimes)) {
            String string = changeData(certificationDeviceTimes);
            wxUserStat.setCertificationDeviceTimes(string);
        }

        String releaseTimes = wxUserStat.getReleaseTimes();
        if (!TextUtils.isEmpty(releaseTimes)) {
            String string = changeData(releaseTimes);
            wxUserStat.setReleaseTimes(string);
        }

        String releaseDeviceTimes = wxUserStat.getReleaseDeviceTimes();
        if (!TextUtils.isEmpty(releaseDeviceTimes)) {
            String string = changeData(releaseDeviceTimes);
            wxUserStat.setReleaseDeviceTimes(string);
        }

        String unCertificationTimes = wxUserStat.getUnCertificationTimes();
        if (!TextUtils.isEmpty(unCertificationTimes)) {
            String string = changeData(unCertificationTimes);
            wxUserStat.setUnCertificationTimes(string);
        }

        String unCertificationDeviceTimes = wxUserStat.getUnCertificationDeviceTimes();
        if (!TextUtils.isEmpty(unCertificationDeviceTimes)) {
            String string = changeData(unCertificationDeviceTimes);
            wxUserStat.setUnCertificationDeviceTimes(string);
        }

        String cumulativeNumber = wxUserStat.getCumulativeNumber();
        if (!TextUtils.isEmpty(cumulativeNumber)) {
            String string = changeData(cumulativeNumber);
            wxUserStat.setCumulativeNumber(string);
        }
        String cumulativeDeviceNumber = wxUserStat.getCumulativeDeviceNumber();
        if (!TextUtils.isEmpty(cumulativeDeviceNumber)) {
            String string = changeData(cumulativeDeviceNumber);
            wxUserStat.setCumulativeDeviceNumber(string);
        }

        return wxUserStat;
    }

    private String changeData(String times) {
        String newData = "";
        if (!TextUtils.isEmpty(times)) {
            float data = Float.parseFloat(times);
            // 期望倍数
            float multiple = PreferenceUtil.getInstance(getContext()).getFloat(PreferenceUtil.EXPECT_MULTIPLE, 1);
            newData = newData + (int) (data * multiple);
        }
        return newData;
    }

    private String getNowTime() {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return format.format(new Date());
    }

    private void getWxUserStatus() {
        BossStatManager.instence().getWxUserStatus(CON_TIME_OUT, SO_TIME_OUT, hospitalValue, new WXUserStateListener() {
            @Override
            public void onSuccess(WxUserStat wxUserStat) {
                if (isAdded()) {
                    if (loading != null) {
                        loading.cancel();
                    }
                    wxUserStat = amplifyData(wxUserStat);

                    Log.i(TAG, "wxUserStat:" + wxUserStat);
                    lastWxUserStat = wxUserStat;
                    lastHospitalName = hospitalName;
                    initData(wxUserStat);

                }
            }

            @Override
            public void onPrepare(String s) {
                initData(null);
                if (loading != null) {
                    loading.show();
                }
            }

            @Override
            public void onFail(int i, String s) {
                if (isAdded()) {
                    if (loading != null) {
                        loading.cancel();
                    }
                    Toast.makeText(context, "数据获取失败", Toast.LENGTH_LONG).show();
                    if (lastWxUserStat != null) {
                        initData(lastWxUserStat);
                    }
                    tvHospitol.setText(lastHospitalName);
                }
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.bt_updata:
                getWxUserStatus();
                break;
            case R.id.rl_hospital_select:
                Intent intent = new Intent(context, SelectHospitalActivity.class);
                intent.putExtra("name", hospitalName);
                intent.putExtra("value", hospitalValue);
                startActivityForResult(intent, 1);
                break;
            case R.id.iv_translate:
                Intent explanIntent = new Intent(context, NounExplanationActivity.class);
                explanIntent.putExtra("type", 0);
                startActivityForResult(explanIntent, 1);
                break;
        }

    }

    /**
     * 返回后有可能期望倍数变了，所以需要再次刷新一次
     */
    public void refreshData() {
//        lastWxUserStat = amplifyData(lastWxUserStat);
//        initData(lastWxUserStat);
        getWxUserStatus();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {


        if (requestCode == 1 && data != null) {
            String name = data.getStringExtra("name");
            String value = data.getStringExtra("value");
            if (hospitalName.equals(name) && hospitalValue.equals(value)) {
                return;
            } else {
                hospitalName = name;
                hospitalValue = value;
                if (!TextUtils.isEmpty(hospitalName)) {
                    tvHospitol.setText(hospitalName);
                    getWxUserStatus();
                }
            }
        }
    }

    @Override
    public void onDestroy() {
        Log.i("log", "onDestroy:公众号页面关闭");
        super.onDestroy();
    }
}
